import 'dart:io';

import 'package:file_picker/file_picker.dart' as filepicker;
import 'package:get/get.dart';
import 'package:rwini_edit/config/config.dart';
import 'package:rwini_edit/view/home/logic.dart';

/// 选择目录获取文件
/// 返回选中的目录
Future<String?> selectDir() async {
  final homelogic = Get.put(HomeLogic());
  // if(Platform.isLinux)
  // 单个文件
  // FilePickerResult? result = await FilePicker.platform.pickFiles();
  //

  // 选择一个目录
  String? selectedDirectory = await filepicker.FilePicker.platform.getDirectoryPath(
    dialogTitle: "选择mod目录",
    // 初始化路径，默认是上一次打开的路径。设置了则打开指定的文件夹路径。Windows系统该参数无效
    initialDirectory: conf.defaultPath,
  );
  if (selectedDirectory == null) {
  } else {
    if (homelogic.listdata.isNotEmpty) {
      // 列表有上次文件
      homelogic.listdata = RxList([]);
    }
    final directory = Directory(selectedDirectory);
    // 列出Documents目录下的文件
    final files = directory.listSync();
    for (var file in files) {
      if (file is File && file.path.endsWith(".ini")) {
        homelogic.listdata.add(file.path);
      } else if (file is Directory) {
        // print('目录: ${file.path}');
      }
    }
    conf.defaultPath = selectedDirectory;
    saveData("defaultPath", selectedDirectory);
  }
  return selectedDirectory;
}

/// 保存文件
/// （String 文件名，List 每一行）
Future saveFile(String filename, List<String> lens) async {
  // // 保存文件/另存为对话框
  String? outputFile = await filepicker.FilePicker.platform.saveFile(
    dialogTitle: '请选择一个输出位置:',
    fileName: filename,
    initialDirectory: conf.nowFilePath,
  );

  if (outputFile != null) {
    File file = File(outputFile);
    var open = file.openWrite();
    for (var len in lens) {
      open.writeln(len);
    }

    await open.close();
  }
}
